package com.yt.order.api.client;

import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.order.models.bo.WorkOrderEvaluationBO;
import com.yt.order.models.bo.WorkOrderEvaluationSaveBO;
import com.yt.order.models.bo.WorkOrderEvaluationQueryBO;
import com.yt.order.models.dto.WorkOrderEvaluationDTO;
import com.yt.order.models.service.IWorkOrderEvaluationService;
import com.yt.order.models.vo.WorkOrderEvaluationVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 工单评价客户端API控制器
 * 提供给前端客户端的评价相关接口
 *
 * @author chen
 * @Date 2025-09-23
 */
@RestController
@RequestMapping("/api/workOrderEvaluation")
@Slf4j
@Api(value = "WorkOrderEvaluationApiController", tags = "工单评价客户端Api接口")
public class WorkOrderEvaluationApiController {

    @DubboReference
    private IWorkOrderEvaluationService workOrderEvaluationService;

    /**
     * 添加工单评价
     * （仅工单状态为"已完成"时可评价）
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加工单评价", notes = "用户对已完成工单进行评价（返回新增的评价详情）")
    public Result<WorkOrderEvaluationVO> add(@RequestBody WorkOrderEvaluationSaveBO saveBO) {
        // 参数校验
        if (saveBO.getOrderId() == null || saveBO.getEvaluatorId() == null
                || saveBO.getEmpId() == null || saveBO.getRating() == null) {
            return new Result<>(CodeEnum.FAIL_100002); // 参数不完整
        }
        if (saveBO.getRating() < 1 || saveBO.getRating() > 5) {
            return new Result<>(CodeEnum.FAIL_100003.getCode(), "评分必须为1-5之间的整数");
        }

        boolean success = workOrderEvaluationService.add(saveBO);
        if (success) {
            // 查询新增的评价信息
            WorkOrderEvaluationDTO dto = workOrderEvaluationService.selectOne(
                    new com.baomidou.mybatisplus.mapper.EntityWrapper<WorkOrderEvaluationDTO>()
                            .eq("order_id", saveBO.getOrderId())
                            .eq("evaluator_id", saveBO.getEvaluatorId())
                            .orderBy("create_time", false)
                            .last("LIMIT 1")
            );
            if (dto == null) {
                return new Result<>(CodeEnum.FAIL_100010); // 评价创建成功但查询失败
            }
            WorkOrderEvaluationVO vo = new WorkOrderEvaluationVO();
            BeanUtils.copyProperties(dto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100007); // 创建失败
    }

    /**
     * 根据工单ID查询评价
     * （查询指定工单的评价详情）
     */
    @GetMapping("/getByOrderId/{orderId}")
    @ApiOperation(value = "根据工单ID查询评价", notes = "查询指定工单的评价详情（仅返回有效评价）")
    @ApiImplicitParam(name = "orderId", value = "工单ID", required = true, paramType = "path", dataType = "Long")
    public Result<WorkOrderEvaluationVO> getByOrderId(@PathVariable("orderId") Long orderId) {
        if (orderId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        WorkOrderEvaluationDTO dto = workOrderEvaluationService.getByOrderId(orderId);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010); // 评价不存在
        }
        WorkOrderEvaluationVO vo = new WorkOrderEvaluationVO();
        BeanUtils.copyProperties(dto, vo);
        return new Result<>(vo);
    }

    /**
     * 分页查询当前用户的评价列表
     * （用户查看自己发起的所有评价）
     */
    @GetMapping("/myEvaluations")
    @ApiOperation(value = "查询用户的评价列表", notes = "分页查询当前用户发起的所有有效评价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "evaluatorId", value = "评价人ID（当前用户ID）", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    public Result<Page<WorkOrderEvaluationVO>> myEvaluations(
            @RequestParam Long evaluatorId,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        if (evaluatorId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        if (pageNo < 1) pageNo = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;

        WorkOrderEvaluationQueryBO bo = new WorkOrderEvaluationQueryBO();
        bo.setEvaluatorId(evaluatorId);
        bo.setPageNo(pageNo);
        bo.setPageSize(pageSize);

        Page<WorkOrderEvaluationVO> resultPage = workOrderEvaluationService.queryEvaluatorEvaluations(bo);
        return new Result<>(resultPage);
    }

    /**
     * 分页查询员工收到的评价列表
     * （员工查看自己收到的所有评价）
     */
    @GetMapping("/empEvaluations")
    @ApiOperation(value = "查询员工收到的评价", notes = "分页查询指定员工收到的有效评价，支持按评分筛选和时间排序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "empId", value = "员工ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "rating", value = "评分筛选（1-5，可选）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "createTimeSort", value = "时间排序（asc-正序，desc-倒序，可选）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    public Result<Page<WorkOrderEvaluationVO>> empEvaluations(
            @RequestParam Long empId,
            @RequestParam(required = false) Integer rating,
            @RequestParam(required = false) String createTimeSort,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        if (empId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        if (pageNo < 1) pageNo = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;

        WorkOrderEvaluationQueryBO bo = new WorkOrderEvaluationQueryBO();
        bo.setEmpId(empId);
        bo.setRating(rating);
        bo.setCreateTimeSort(createTimeSort);
        bo.setPageNo(pageNo);
        bo.setPageSize(pageSize);

        Page<WorkOrderEvaluationVO> resultPage = workOrderEvaluationService.queryEmpEvaluations(bo);
        return new Result<>(resultPage);
    }

    /**
     * 更新评价内容
     * （仅评价发起者可修改，且评价创建后24小时内可修改）
     */
    @PutMapping("/update/{id}")
    @ApiOperation(value = "更新评价内容", notes = "修改评价内容（仅创建后24小时内可修改）")
    @ApiImplicitParam(name = "id", value = "评价ID", required = true, paramType = "path", dataType = "Long")
    public Result<WorkOrderEvaluationVO> update(
            @PathVariable("id") Long id,
            @RequestBody WorkOrderEvaluationSaveBO saveBO) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 校验评价是否存在
        WorkOrderEvaluationDTO existingDto = workOrderEvaluationService.selectById(id);
        if (existingDto == null) {
            return new Result<>(CodeEnum.FAIL_100010); // 评价不存在
        }

        // 校验是否为评价发起者
        if (!existingDto.getEvaluatorId().equals(saveBO.getEvaluatorId())) {
            return new Result<>(CodeEnum.FAIL_100013.getCode(), "无权修改他人评价");
        }

        // 校验是否在可修改时间范围内（创建后24小时内）
        long createTime = existingDto.getCreateTime().getTime();
        long now = System.currentTimeMillis();
        if (now - createTime > 24 * 60 * 60 * 1000) {
            return new Result<>(CodeEnum.FAIL_100014.getCode(), "评价创建超过24小时，不可修改");
        }

        // 复制更新字段
        WorkOrderEvaluationDTO updateDto = new WorkOrderEvaluationDTO();
        BeanUtils.copyProperties(saveBO, updateDto);
        updateDto.setId(id);
        updateDto.setRevision(existingDto.getRevision()); // 携带乐观锁版本号

        boolean success = workOrderEvaluationService.updateById(updateDto);
        if (success) {
            WorkOrderEvaluationDTO updatedDto = workOrderEvaluationService.selectById(id);
            WorkOrderEvaluationVO vo = new WorkOrderEvaluationVO();
            BeanUtils.copyProperties(updatedDto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100008); // 更新失败
    }

    /**
     * 逻辑删除评价（设置状态为无效）
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除评价", notes = "逻辑删除评价（设置状态为无效）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "评价ID", required = true, paramType = "path", dataType = "Long"),
            @ApiImplicitParam(name = "operatorId", value = "操作人ID（验证权限）", required = true, paramType = "query", dataType = "Long")
    })
    public Result<Void> delete(
            @PathVariable("id") Long id,
            @RequestParam Long operatorId) {
        if (id == null || operatorId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        WorkOrderEvaluationDTO dto = workOrderEvaluationService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010); // 评价不存在
        }

        // 逻辑删除（设置状态为0）
        dto.setStatus(0);
        dto.setRevision(dto.getRevision()); // 携带乐观锁版本号
        boolean success = workOrderEvaluationService.updateById(dto);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009); // 删除失败
    }

}